package com.ecommerce.dao;

import com.ecommerce.model.CartItem;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CartDAO {

    public boolean addToCart(CartItem cartItem) {
        // 先检查是否已经存在相同的商品
        String checkSql = "SELECT id, quantity FROM cart_items WHERE user_id = ? AND product_id = ?";
        String insertSql = "INSERT INTO cart_items (user_id, product_id, quantity) VALUES (?, ?, ?)";
        String updateSql = "UPDATE cart_items SET quantity = quantity + ? WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection()) {
            // 检查是否已存在
            PreparedStatement checkStmt = conn.prepareStatement(checkSql);
            checkStmt.setInt(1, cartItem.getUserId());
            checkStmt.setInt(2, cartItem.getProductId());
            ResultSet rs = checkStmt.executeQuery();

            if (rs.next()) {
                // 已存在，更新数量
                int existingId = rs.getInt("id");
                PreparedStatement updateStmt = conn.prepareStatement(updateSql);
                updateStmt.setInt(1, cartItem.getQuantity());
                updateStmt.setInt(2, existingId);
                int rowsAffected = updateStmt.executeUpdate();
                return rowsAffected > 0;
            } else {
                // 不存在，插入新记录
                PreparedStatement insertStmt = conn.prepareStatement(insertSql);
                insertStmt.setInt(1, cartItem.getUserId());
                insertStmt.setInt(2, cartItem.getProductId());
                insertStmt.setInt(3, cartItem.getQuantity());
                int rowsAffected = insertStmt.executeUpdate();
                return rowsAffected > 0;
            }

        } catch (SQLException e) {
            System.out.println("添加到购物车失败: " + e.getMessage());
            return false;
        }
    }

    public List<CartItem> getCartItemsByUserId(int userId) {
        List<CartItem> cartItems = new ArrayList<>();
        String sql = "SELECT ci.*, p.name as product_name, p.price as product_price " +
                "FROM cart_items ci " +
                "JOIN products p ON ci.product_id = p.id " +
                "WHERE ci.user_id = ? AND p.status = 'active'";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, userId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                CartItem item = new CartItem();
                item.setId(rs.getInt("id"));
                item.setUserId(rs.getInt("user_id"));
                item.setProductId(rs.getInt("product_id"));
                item.setProductName(rs.getString("product_name"));
                item.setProductPrice(rs.getDouble("product_price"));
                item.setQuantity(rs.getInt("quantity"));
                cartItems.add(item);
            }

        } catch (SQLException e) {
            System.out.println("获取购物车商品失败: " + e.getMessage());
        }

        return cartItems;
    }

    public boolean updateCartItemQuantity(int cartItemId, int quantity) {
        if (quantity <= 0) {
            // 如果数量为0或负数，删除该商品
            return deleteCartItem(cartItemId);
        }

        String sql = "UPDATE cart_items SET quantity = ? WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, quantity);
            stmt.setInt(2, cartItemId); // WHERE条件

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("更新购物车商品数量失败: " + e.getMessage());
            return false;
        }
    }

    public boolean deleteCartItem(int cartItemId) {
        String sql = "DELETE FROM cart_items WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, cartItemId); // WHERE条件
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("删除购物车商品失败: " + e.getMessage());
            return false;
        }
    }

    public boolean clearUserCart(int userId) {
        String sql = "DELETE FROM cart_items WHERE user_id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, userId); // WHERE条件
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("清空购物车失败: " + e.getMessage());
            return false;
        }
    }

    public CartItem getCartItemById(int cartItemId) {
        String sql = "SELECT ci.*, p.name as product_name, p.price as product_price " +
                "FROM cart_items ci " +
                "JOIN products p ON ci.product_id = p.id " +
                "WHERE ci.id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, cartItemId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                CartItem item = new CartItem();
                item.setId(rs.getInt("id"));
                item.setUserId(rs.getInt("user_id"));
                item.setProductId(rs.getInt("product_id"));
                item.setProductName(rs.getString("product_name"));
                item.setProductPrice(rs.getDouble("product_price"));
                item.setQuantity(rs.getInt("quantity"));
                return item;
            }

        } catch (SQLException e) {
            System.out.println("获取购物车商品失败: " + e.getMessage());
        }

        return null;
    }
}